import {Reducer, Effect, Subscription} from 'umi'
import {editRecord, getRemoteList, addRecord, deleteRecord, queryList, getUserInfoById} from "@/services/users";
import {message} from "antd";

interface UserModelType {
  namespace: string;
  state: {
    userList: any[],
    total: Number,
    data: {},
  };
  reducers: {
    getList: Reducer,
    getUserInfo: Reducer,
  };
  effects: {
    getRemote: Effect,
    editRecord: Effect,
    addRecord: Effect,
    deleteRecord: Effect,
    getQueryList: Effect,
    getUserInfoById: Effect,
  };
}

const Usermodel: UserModelType = {
  namespace: 'users',
  state: {
    userList: [],
    total: 0,
    data: {},
  },
  reducers: {
    getList(state, {payload}) {
      return {
        ...state,
        userList: payload.list,
        total: payload.total,
        pageNum: payload.pageNum,
      }
    },
    getUserInfo(state, {payload}) {
      return {
        data: payload
      }
    }
  },
  effects: {
    * getRemote({payload}, {put, call}) {
      const {data} = yield call(getRemoteList, {pageNum: payload ? payload : 1, pageSize: 5});
      yield put({
        type: 'getList',
        payload: data,
      })
    },
    *editRecord({payload}, {put, call}) {
      const {code} = yield call(editRecord, payload)
      if(code === 200) {
        message.success("修改成功")
      } else {
        message.error("System Error")
      }
    },
    *addRecord({payload}, {put, call}) {
      const {code} = yield call(addRecord, payload)
      if(code === 200) {
        message.success("添加成功")
      } else {
        message.error("System Error")
      }
    },
    *deleteRecord({payload}, {put, call}) {
      const {code} = yield call(deleteRecord, payload)
      if(code === 200) {
        message.success("删除成功")
      } else {
        message.error("System Error")
      }
    },
    *getQueryList({payload}, {put, call}) {
      const {data} = yield call(queryList, {queryDto: payload, pageNum: 1, pageSize: 5, queryUsername: payload});
      yield put({
        type: 'getList',
        payload: data,
      })
    },
    *getUserInfoById({payload}, {put, call}) {
      const {data} = yield call(getUserInfoById, payload);
      yield put({
        type: 'getUserInfo',
        payload: data,
      })
    }
  },
}

export default Usermodel
